<template>
  <base-panel :show.sync="visible" :width="panelWidth">
    <h3 slot="title">
      <span>{{ $t('component.advancedSearch.title') }}</span>
      <el-dropdown
        class="pull-right"
        trigger="click"
        @command="setAdvanceSearchColumn"
      >
        <i
          class="iconfont icon-xitongguanli customer-panel-btn"
          style="float: none;"
        ></i>

        <el-dropdown-menu slot="dropdown" class="customer-advance-setting">
          <el-dropdown-item command="1">{{$t('common.base.table.oneCl')}}</el-dropdown-item>
          <el-dropdown-item command="2">{{$t('common.base.table.twoCl')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </h3>
    <el-form label-position="top" class="advanced-search-form" onsubmit="return false;">
      <search-form
        :fields="fields"
        ref="searchForm"
        :form-backup="formBackup"
        :column-num="columnNum"
        :catalogOption="catalogOption"
      ></search-form>
      <slot name="footer"></slot>
    </el-form>
  </base-panel>
</template>

<script>
import {
  FormFieldMap,
  SettingComponents,
} from "@src/component/form/components";
import * as Utils from "@src/component/form/util";
import { formatDate } from "pub-bbx-utils";
import _ from "lodash";
import { isEmptyStringObject } from "@src/util/function";
/* service */
import { getFieldSearchComponent } from '@service/FormService.ts'
import { isQualityTimeField, isQualityRuleStartTimeField } from '@service/FieldService.ts'
import { convertFormQualityRuleFieldValueToQualityRuleSearchFormData } from '@service/QualityRuleService.ts'

import { getTreeList } from '@src/api/ProductV2Api';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { formatAddress } from 'pub-bbx-utils';
import { baseDistValueToObject, searchAddressObjectParams } from '@src/util/addressUtil';
export default {
  name: "search-panel",
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      visible: false,
      formBackup: {},
      columnNum: 1,
      catalogOption: []
    };
  },
  computed: {
    fields() {
      const isSystemSearch = ['relationMaterials','relatedServiceItem'];
      let f = {};
      let fields = [...this.config.fields]
        .filter((f) =>(f.isSearch || (f.isSystem && !isSystemSearch.includes(f.formType))) && f.formType !== 'attachment')
        .map((field) => {
          f = _.cloneDeep(field);

          let formType = f.formType;

          if (formType === "datetime") {
            formType = "date";
          }

          if (f.fieldName === "customer") {
            formType = "customer";
          }

          if (formType === "updateTime") {
            f.displayName = this.$t('common.fields.updateTime.displayName');
          }

          if(f.fieldName === 'pathName'){
            Object.assign(f, {
              fieldName: 'parentIds'
            })
            formType = 'tree'
          }

          if(f.fieldName === 'catalogName'){
            f.maxlength = 30;
          }

          if(f.fieldName === 'catalogNum'){
            f.maxlength = 50;
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
            operator: this.matchOperator(f),
          });
        })
        .sort((a, b) => a.orderId - b.orderId);
      return fields;
    },
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
  },
  mounted() {
    const { column_number } = this.getLocalStorageData();
    if (column_number) this.columnNum = Number(column_number);

    this.getCatalogOption()
  },
  methods: {
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      localStorage.setItem(
        "product_menu_list_localStorage_19_4_24",
        JSON.stringify(data)
      );
    },
    getLocalStorageData() {
      const dataStr = localStorage.getItem("product_menu_list_localStorage_19_4_24") || "{}";
      return JSON.parse(dataStr);
    },
    matchOperator(field) {
      let formType = field.formType;
      let operator = "";

      switch (formType) {
      case "date": {
        operator = "between";
        break;
      }
      case "datetime": {
        operator = "between";
        break;
      }
      case "select": {
        if (field.setting && field.setting.isMulti) {
          operator = "contain";
        } else {
          operator = "eq";
        }
        break;
      }
      case "cascader": {
        operator = "cascader";
        break;
      }
      case "user": {
        operator = "user";
        break;
      }
      case "address": {
        operator = "address";
        break;
      }
      case "location": {
        operator = "location";
        break;
      }
      case "related_task": {
        operator = "array_eq";
        break;
      }
      case "formula": {
        operator = "eq";
        break;
      }
      default: {
        operator = "like";
        break;
      }
      }
      return operator;
    },
    resetParams() {
      this.formBackup = {};
      this.$refs.searchForm
        && this.$nextTick(this.$refs.searchForm.initFormVal);
    },

    buildParams() {
      const form = this.$refs.searchForm.returnData();
      this.formBackup = Object.assign({}, form);

      const isSystemFields = this.fields.filter((f) => f.isSystem);
      const notSystemFields = this.fields.filter((f) => !f.isSystem);
      let params = {
        conditions: [],
      };

      let tv = null;
      let fn = "";

      for (let i = 0; i < isSystemFields.length; i++) {
        tv = isSystemFields[i];
        fn = tv.fieldName;

        // hasRemind
        if (fn === "hasRemind" && form[fn] !== "") {
          params.hasRemind = form[fn] == 2 ? 0 : form[fn];
          continue;
        }

        if (fn === "qrcodeState" && form[fn] !== "") {
          params.qrcodeState = form[fn] == 2 ? 0 : form[fn];
          continue;
        }

        if (fn == "area") {
          const address = baseDistValueToObject(form[fn])
          params.productAddress = {
            ...(params.productAddress || {}),
            ...(searchAddressObjectParams(address))
          };
          continue;
        }

        if (fn === "addressDetail") {
          params.productAddress = {
            ...(params.productAddress || {}),
            address: form[fn],
          };
          continue;
        }

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }
        
        if (['date', 'datetime'].includes(tv.formType)) {
          params[`${fn}Start`] = form[fn][0];
          params[`${fn}End`] = form[fn][1];
          continue;
        }

        if (tv.formType === "tags") {
          params.tagId = form[fn].map(({ id }) => id).join("");
        }

        // 产品关联物料
        if (tv.formType === 'relationMaterials') {
          params['materielId'] = form[fn][0].id;
          continue;
        }

        // 关联服务项目
        if (tv.formType === 'relatedServiceItem') {
          params['relatedServiceItem'] = form[fn].map(({ id }) => id);
          continue;
        }
        
        if (isQualityRuleStartTimeField(tv) || isQualityTimeField(tv)) {
          const qualityRuleTimeValue = convertFormQualityRuleFieldValueToQualityRuleSearchFormData(form)

          // dataType 1 关联产品日期  0 自定义日期显示
          if (tv?.setting?.dataType === 1) {
            delete qualityRuleTimeValue.qualityStartDate
          } else if (tv?.setting?.dataType === 0) {
            delete qualityRuleTimeValue.qualityFiledName
          }

          Object.keys(qualityRuleTimeValue).forEach(key => {
            params[key] = qualityRuleTimeValue[key]
          })
          continue
        }

        if (typeof form[fn] === "string" || typeof form[fn] === "number") {
          params[fn === "customer" ? "customerId" : fn] = form[fn];
          continue;
        }

        if (tv.formType === "tree") {
          params[fn] = form[fn]
        }
      }

      for (let i = 0; i < notSystemFields.length; i++) {
        let key = null;
        tv = notSystemFields[i];
        fn = tv.fieldName;

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        // 空对象
        if (
          typeof form[fn] === "object"
          && !Array.isArray(form[fn])
          && !Object.keys(form[fn]).length
        ) {
          continue;
        }

        if (['date', 'datetime'].includes(tv.originalFormType)) {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            betweenValue1: form[fn][0],
            betweenValue2: form[fn][1],
          });
          continue;
        }

        if (tv.formType === "cascader") {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            inValue: form[fn],
          });
          continue;
        }

        if (tv.formType === "address") {
          let address = {
            property: fn,
            operator: tv.operator,
          };
          let isEmpty = isEmptyStringObject(form[fn]);

          if (!isEmpty) {
            address.value = formatAddress(form[fn],'');
          }
          params.conditions.push(address);
          continue;
        }

        if (tv.originalFormType === "related_task") {
          key = "taskNo";
        }

        params.conditions.push({
          property: fn,
          operator: tv.operator,
          value: form[fn],
          key,
        });
      }

      // 返回接口数据
      return params;
    },
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      this.saveDataToStorage("column_number", command);
    },
    open() {
      this.visible = true;
    },
    // 获取树结构
    async getCatalogOption () {
      try{
        let {code,result,message} = await getTreeList({conData:0});
        if(code === 0) {
          this.deleteEmpty(result);
          this.catalogOption = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty (list) {
      list.forEach(item => {
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
  },
  components: {
    SearchForm: {
      name: "search-form",
      props: {
        fields: {
          type: Array,
          default: () => [],
        },
        formBackup: {
          type: Object,
          default: () => ({}),
        },
        columnNum: {
          type: Number,
          default: 1,
        },
        catalogOption: Array
      },
      data() {
        return {
          form: {},
          tableName: "product",
        };
      },
      mounted() {
        this.buildForm();
      },
      methods: {
        normalizer(node) {
          return {
            id: node.id,
            label: node.name,
            children: node.tasks,
          }
        },


        returnData() {
          return Object.assign({}, this.form);
        },
        buildForm() {
          if (Object.keys(this.form).length === this.fields.length) return;
          this.initFormVal();
        },
        initFormVal() {
          let fields = this.fields;
          let form = {};
          let tv = "";

          fields.forEach((field) => {
            tv = "";
            // 地址的默认值初始化为对象
            if (
              field.formType == "customerAddress"
              || field.formType == "address"
            )
              tv = {};
            if (field.formType == "date" || field.formType == "datetime")
              tv = [];
            if (field.formType === "link") {
              tv = {};
            }
            if (field.formType === "tags") {
              tv = [];
            }
            if (field.formType === "area") {
              tv = [];
            }
            if (field.formType === "area") {
              tv = [];
            }
            if (field.formType === "cascader") {
              tv = [];
            }
            if (field.formType === "tree") {
              tv = [];
            }
            if (field.formType === "relatedServiceItem") {
              tv = [];
            }
            form[field.fieldName] = this.formBackup[field.fieldName] || tv;

            this.$set(
              this.form,
              field.fieldName,
              this.formBackup[field.fieldName] || tv
            );
          });

          return form;
        },
        update(event, action) {

          if (action === "tags") {
            return this.$set(this.form, "tags", event);
          }

          if (action === "dist") {
            return this.$set(this.form, "area", event);
          }
          const f = event.field;
          this.$set(this.form, f.fieldName, event.newValue);
        },
        createUserInput(event, isTags) {
          if (isTags) {
            return (this.form.tags = event);
          }
          const f = event.field;
          this.form[f.fieldName] = event.keyword;
        },
        renderInput(h, field) {
          const f = {
            ...Object.freeze(field),
          };

          let comp = FormFieldMap.get(f.formType);

          if (
            !comp
            && f.formType !== "tags"
            && f.formType !== "area"
            && f.formType !== "linkman"
            && f.formType !== "tree"
          ) {
            return null;
          }

          if (f.formType === "select" || f.formType === 'text') {
            f.setting?f.setting.isMulti = false:f.setting={isMulti:false};
          }

          let childComp = null;

          if (f.formType === "tags") {
            childComp = h("biz-team-select", {
              props: {
                value: this.form[f.fieldName],
              },
              on: {
                input: (event) => this.update(event, "isTags"),
              },
            });
          } else if (f.formType === "linkman") {
            childComp = h("linkman-search", {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => {
                  this.update(event);
                },
                input: (event) => {
                  this.form[f.fieldName] = event.keyword;
                },
              },
            });
          } else if (f.formType === "area") {
            childComp = h("base-dist", {
              props: {
                value: this.form[f.fieldName],
              },
              on: {
                input: (event) => this.update(event, "dist"),
              },
            });
          } else if (f.formType === "customer") {
            childComp = h("customer-search", {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => this.update(event),
              },
            });
          } else if (f.formType === "user") {
            childComp = h("user-search", {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => this.update(event),
                input: (event) => {
                  this.form[f.fieldName] = event.keyword;
                },
              },
            });
          } else if (f.formType === "tree") {
            childComp =  h('treeselect', {
              props: {
                value: this.form[f.fieldName],
                multiple: true,
                limit: 1,
                placeholder: this.$t('product.productType.placeholder.productMenuTree'),
                options: this.catalogOption,
                normalizer: this.normalizer,
                'value-consists-of': 'LEAF_PRIORITY',
                limitText: count => `+ ${count}`,
                noOptionsText: this.$t('common.base.tip.noData'),
                noResultsText: this.$t('common.base.tip.noData')
              },
              on: {
                input: (value) => {
                  this.form[f.fieldName] = value
                }
              }
            })
          } else if (f.formType === 'relationMaterials') {
            childComp = h("form-related-material-build", {
              props: {
                field: f,
                value: this.form[f.fieldName] || [],
                disableMap: true,
              },
              on: {
                update: (event) => this.update(event)
              },
            });
          } else {
            const searchComponent = getFieldSearchComponent({ ...f, component: comp })
            
            childComp = h(
              searchComponent,
              {
                props: {
                  field: f,
                  value: this.form[f.fieldName],
                  disableMap: true,
                  placeholder: Utils.genPlaceholder(f),
                },
                on: {
                  update: (event) => this.update(event),
                },
              }
            );
          }

          return h(
            "form-item",
            {
              props: {
                label: f.displayName,
                needValidate: false,
              },
            },
            [childComp]
          );
        },
      },
      render(h) {
        return (
          <div
            class={`form-item-container ${
              this.columnNum == 2 ? "two-columns" : ""
            }`}
          >
            {this.fields.map((f) => this.renderInput(h, f))}
          </div>
        );
      },
      components: { Treeselect, ...SettingComponents },
    },
  },
};
</script>

<style lang="scss">
.advanced-search-form {
  overflow: auto;
  padding: 10px 15px 63px 15px;

  height: calc(100% - 52px);
  justify-content: space-between;

  .two-columns {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 50%;
    }
  }

  .form-item-container {
    justify-content: space-between;
  }

  .form-item {
    label {
      padding-left: 0;
    }

    width: 390px;
  }

  .advanced-search-btn-group {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    position: absolute;
    bottom: 0px;
    background: #fff;
    padding: 15px 20px;

    .base-button {
      margin: 0 10px;
    }
  }
}
</style>
<style lang="scss" scoped>
  ::v-deep .vue-treeselect__multi-value-item {
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    border-radius: 4px;
    .vue-treeselect__multi-value-label {
      max-width: 112px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      color: #909399;
    }
    .vue-treeselect__value-remove {
      color: #909399;
      border: 0;
      padding: 0 10px 0 0;
      svg {
        box-sizing: content-box;
        padding: 3px;
        background-color: #c0c4cc;
        border-radius: 50%;
        &:hover {
          background-color: $color-primary-light-6;
          color: #fff;
        }
      }
    }
  }
  ::v-deep .vue-treeselect__limit-tip-text {
    height: 22px;
    line-height: 18px;
    margin: 0;
    background-color: #f4f4f5;
    border: 1px solid #e9e9eb;
    padding: 1px 5px;
    border-radius: 4px;
    font-weight: normal;
    color: #909399;
  }
  ::v-deep .vue-treeselect__x-container {
    &:hover {
      color: #ccc;
    }
  }
  @mixin bgColor {
    border-color: $color-primary-light-6;
    background: $color-primary-light-6;
  }
  ::v-deep .vue-treeselect__checkbox--checked {
    @include bgColor;
    &:hover {
      @include bgColor;
    }
  }
  ::v-deep .vue-treeselect__label-container:hover {
    .vue-treeselect__checkbox--checked {
      @include bgColor;
    }
    .vue-treeselect__checkbox--unchecked {
      border-color: $color-primary-light-6;
    }
  }
</style>